<template>
  <div class="file">
    <div class="header">
      <x-header :left-options="{ backText: '' }">
        <header-title :title="$t('file.staticResourceDownload')" />
        <a slot="right" @click="uploadFile">{{ $t('common.upload') }}</a>
      </x-header>
    </div>

    <div class="file-list">
      <divider class="divider-top">{{ $t('file.staticResourceNote') }}</divider>
      <group :title="$t('file.jssdkFileDownload')">
        <cell
          v-for="(file, index) in files"
          :key="index"
          :title="file.filename"
          :value="file.sizeName"
          @click.native="changeFileStatus(file)"
        >
          <div slot="child" class="icon-download">
            <icon v-if="file.status === 0" type="download" />
            <inline-loading v-if="file.status === 2" />
            <icon v-if="file.status === 1" type="success" />
          </div>
        </cell>
      </group>
      <group :title="$t('file.jssdkFileLookOverOnline')">
        <cell
          v-for="(file, index) in files"
          :key="index"
          :title="file.filename"
          :value="file.sizeName"
          @click.native="jssdkOpenFileUrl(file)"
        >
          <div slot="child" class="icon-download">
            <icon type="info" />
          </div>
        </cell>
      </group>
      <group :gutter="0">
        <div class="tips-box">
          <p>{{ $t('file.browserLookOver') }}</p>
          <p class="tips">{{ $t('file.iosOpenFileTips') }}</p>
        </div>
        <cell
          v-for="(file, index) in files"
          :key="index"
          :title="file.filename"
          :value="file.sizeName"
          @click.native="openFileUrl(file.filePath)"
        >
          <div slot="child" class="icon-download">
            <icon type="info" />
          </div>
        </cell>
      </group>
      <group :title="$t('file.largeFileUpload')">
        <cell :title="$t('file.selectFile')" is-link @click.native="handleChoiceLargeFile"/>
      </group>
      <group :title="$t('file.sameFileDownloadTest')">
        <cell
          v-for="(file, index) in sameFiles"
          :key="index"
          :title="file.filename"
          :value="file.sizeName"
          @click.native="changeFileStatus(file)"
        >
          <div slot="child" class="icon-download">
            <icon v-if="file.status === 0" type="download" />
            <inline-loading v-if="file.status === 2" />
            <icon v-if="file.status === 1" type="success" />
          </div>
        </cell>
      </group>
    </div>
    <div v-transfer-dom>
      <loading :show="isLoading" :text="loadingText" />
    </div>
  </div>
</template>

<script>
import md5 from 'js-md5';
import { mapState, mapMutations } from 'vuex';
import {
  XHeader,
  Group,
  Cell,
  Icon,
  Loading,
  InlineLoading,
  Divider,
} from 'vux';
import HeaderTitle from '@/components/common/HeaderTitle';
import { getFilesApi, fileUpload } from '@/api/file';
import { isIos } from '@/utils/index';
import { domain } from '@/utils/http';

export default {
  components: {
    Icon,
    Group,
    Cell,
    XHeader,
    Loading,
    HeaderTitle,
    InlineLoading,
    Divider,
  },
  data() {
    return {
      files: [],
      sameFiles: [],
      client: {}, // 豆豆客户端信息
      isDownload: false,
      search: {
        page: 1,
        size: 100,
        accountId: null,
      },
    };
  },
  computed: {
    ...mapState(['fileStatus', 'isLoading', 'loadingText']),
  },
  created() {
    this.getClientInfo();
    this.getFiles();
    // 进度通知只需注册一次
    vrv.jssdk.registerProgressNotice({
      success: res => {
        this.$nextTick(() => {
          this.setLoadingText(`${res.progress}%`);
        });
      },
    });
  },
  methods: {
    ...mapMutations(['updateFileStatus', 'setIsLoading', 'setLoadingText']),
    setFileStatus(file) {
      const data = {
        key: file.key,
        value: {
          status: file.status,
          localPath: file.localPath,
        },
      };
      this.updateFileStatus(data);
    },
    async getFiles() {
      const res = await getFilesApi(this.search);
      res.data.forEach(item => {
        if (item.staticFilePath) {
          item.filePath = `${domain}${item.staticFilePath}`;
        }
        item.key = item.staticFilePath ? md5(item.staticFilePath) : null;
        const fileStatus = this.fileStatus[item.key];
        if (fileStatus) {
          item.status = fileStatus.status;
          item.localPath = fileStatus.localPath;
        } else {
          item.status = 0;
          item.localPath = null;
        }
        item.sizeName = this.getFileSizeText(item.size);
        item.filename = item.name;
      });
      this.files = res.data;

      // 同名文件下载测试数据
      let lastItem;
      this.sameFiles = [];
      for (const item of this.files) {
        if (!lastItem) {
          lastItem = Object.assign({}, item);
          lastItem.key = 'sameFiledownloadTestOne';
          this.sameFiles.push(lastItem);
        } else if (item.filePath !== lastItem.filePath) {
          const secondItem = Object.assign({}, item);
          secondItem.key = 'sameFiledownloadTestTwo';
          secondItem.filename = lastItem.filename;
          this.sameFiles.push(secondItem);
          break;
        }
      }
    },
    getFileSizeText(fileSize) {
      if (!fileSize) {
        return '0B';
      }
      if (fileSize < 1024) {
        return `${fileSize}B`;
      }
      if (fileSize < 1024 * 1024) {
        const text = Math.floor(fileSize / 1024);
        return `${text}KB`;
      }
      if (fileSize < 1024 * 1024 * 1024) {
        const text = Math.floor(fileSize / (1024 * 1024));
        return `${text}MB`;
      }
    },
    uploadFile() {
      vrv.jssdk.getLocalFiles({
        type: 10020,
        rootType: 0,
        upload: true,
        success: async res => {
          console.log(res, 'jssdk返回的值');
          if (res.resultCode === 0) {
            const uploadFiles = [];
            res.mFilePath.forEach((item, index) => {
              uploadFiles.push({
                filename: res.mFileName[index],
                fileUrl: item,
              });
            });
            await fileUpload(uploadFiles);
            this.getFiles();
            this.$vux.toast.show({
              text: this.$t('file.fileUploadSuccessfully'),
              time: 2000,
            });
          }
          this.setIsLoading(false);
        },
      });
      // FIXME(CFY) pc 取消选择文件没有返回相应状态，在 pc 上传文件暂时不显示进度
      if (this.client.platform && this.client.platform.toLowerCase() !== 'pc') {
        this.setLoadingText('0%');
        this.setIsLoading(true);
      }
    },
    fileExists(file) {
      if (!file.filePath) {
        this.$vux.toast.show({
          type: 'text',
          width: '20em',
          text: this.$t('file.fileNotSyncSuccessfully'),
          time: 2000,
        });
        this.getFiles();
        return false;
      }
      return true;
    },
    changeFileStatus(file) {
      if (file.status === 0 && this.fileExists(file)) {
        this.jssdkDownloadFile(file);
      } else if (file.status === 1) {
        this.jssdkOpenFilePath(file);
      }
    },
    jssdkDownloadFile(file) {
      // 计算下载文件名称
      let downloadName = file.filename;
      const suffix = md5(file.filePath);
      const index = downloadName.lastIndexOf('.');
      if (index > 0) {
        const filename = downloadName.substring(0, index);
        const fileType = downloadName.substr(index);
        downloadName = `${filename}(${suffix})${fileType}`;
      }

      // 设置文件状态为下载中
      file.status = 2;
      this.setFileStatus(file);

      console.log(file.filePath, '文件路径');
      // jssdk 下载文件
      vrv.jssdk.downloadFile({
        type: 2,
        url: encodeURI(file.filePath),
        fileName: downloadName,
        savePath: 'LinkdoodSDK/collect',
        success: res => {
          console.log(res, 'jssdk返回的值');
          // FIXME(ZK) 目前后端通过定时任务去获取 jssdk 上传到豆豆服务器的文件，所以
          // 有时候可能没有获取到就下载了，目前测试返回的是 -1
          if (res.resultCode === 0) {
            file.status = 1;
            file.localPath = res.resultPath;
          } else {
            file.status = 0;
            this.$vux.toast.show({
              type: 'warn',
              text: this.$t('file.downloadFailed'),
              time: 2000,
            });
          }
          this.setFileStatus(file);
        },
      });
    },
    jssdkOpenFilePath(file) {
      if (file.status !== 1) {
        this.$vux.toast.show({
          type: 'warn',
          text: this.$t('file.fileNotExist'),
          time: 2000,
        });
        return;
      }
      vrv.jssdk.openFilePath({
        type: 1,
        path: file.localPath,
        success: res => {
          if (res.resultCode === -1) {
            file.status = 0;
            this.setFileStatus(file);
            this.$vux.toast.show({
              type: 'warn',
              text: this.$t('file.fileNotExist'),
              time: 2000,
            });
          }
        },
      });
    },
    jssdkOpenFileUrl(file) {
      if (!file.filePath) {
        this.$vux.toast.show({
          type: 'text',
          width: '20em',
          text: this.$t('file.fileNotSyncSuccessfully'),
          time: 2000,
        });
        return;
      }
      
      vrv.jssdk.openFileURL({
        url: encodeURI(file.filePath),
        name: file.filename,
        success: res => {
          console.log('open file res', res);
          if (res.resultCode === -1) {
            this.$vux.toast.show({
              type: 'warn',
              text: this.$t('file.fileNotSyncSuccessfully'),
              time: 2000,
            });
          }
        },
      });
    },
    openFileUrl(fileUrl) {
      // window.open只能在安卓中打开链接，ios不执行
      if (isIos()) {
        this.$vux.toast.show({
          type: 'text',
          width: '16em',
          text: this.$t('file.noSupportIos'),
        });
        return;
      }
      window.location.href = fileUrl;
    },
    getClientInfo() {
      vrv.jssdk.getClientInfo({
        success: res => {
          console.log(res, 'Jssdk获取客户端信息');
          this.client = res;
        },
      });
    },
    handleChoiceLargeFile() {
      let uploadText = '0%';
      let showLoading = false;
      const url = `${domain}/app-template/api/files/upload/base64`;
      vrv.jssdk.getLargeFileToLocal({
        path: '/', // 默认打开路径
        burstSize: 1024 * 1024, // 分片大小，默认1M，单位byte
        url,
        exeQueueSize: 5,
        chunkRetry: false,
        isBreakpoint: false,
        isVerification: false,
        progress: (progress) => {
          uploadText = `${progress}%`;
          if (!showLoading) {
            this.$vux.loading.show({
              text: uploadText,
            });
            showLoading = true;
          }
        },
        success: (res) => {
          this.$vux.loading.hide();
          console.log('large file upload success. res value', res);
        },
        error: (status, xhr) => {
          this.$vux.loading.hide();
          console.log('large file upload error. error message', status, xhr);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.file {
  height: 100%;
  overflow: hidden;
  .header {
    position: relative;
    height: 45px;
  }
  /deep/ .vux-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10;
  }
  .file-list {
    position: relative;
    width: 100%;
    height: calc(100% - 45px);
    margin-top: 60px;
    overflow-y: auto;
    .divider-top {
      margin-top: 15px;
    }
    .icon-download {
      width: 33px;
      margin-left: 10px;
      text-align: center;
    }
  }
  .tips-box {
    background: #f5f5f5;
    padding: 25px 30px 10px 30px;
    font-size: 28px;
    color: #999999;
    .tips {
      color: #F00;
    }
  }
}
</style>
